﻿using UnityEngine;
using System.Collections;

//Magic Balls are expected to be "hide" and "display" rather than create/destroy
//this is to save processing power in creating/destroy, and recycle the resources
public class MagicBall : MonoBehaviour {
	public Utility util;
	//positive value = direction to the right
	public int direction = 1;
	public float speedX = 10;
	public bool isVisible;

	public float countDown;

	// Use this for initialization
	void Start () {
		isVisible = false;
		countDown = 0;
	}
	
	// Update is called once per frame
	void Update () {
		if(isVisible){

			transform.position = new Vector2(transform.position.x + (speedX*Time.deltaTime*this.direction), transform.position.y);

			if(countDown > 0 ){
				countDown -= Time.deltaTime;
			}else{
				//if countDown ends, then "hide" magic ball
				makeMagicBallDisappear();
			}
		}
	}

	void OnTriggerEnter2D(Collider2D collidedObj){
		Debug.Log("MagicBall onTriggerEnter(), collidedObj tag: " + collidedObj.gameObject.tag);
		if( "Monsters".Equals(collidedObj.gameObject.tag) ){
			int damage = 10;
			Monster mobScript = collidedObj.gameObject.GetComponent<Monster>();
			if(!mobScript.isDying){
				mobScript.HP -= damage;
				//mob's Y need to +1 because the coordinate we have is calculate from the center of the sprite, 
				//and we want to make sure the number appears ABOVE the sprite (not from the center);
				util.displayDamageNumber(damage.ToString(), new Vector2(mobScript.transform.position.x, mobScript.transform.position.y+1f));
				if(mobScript.HP <= 0){
					mobScript.startDyingAnimation();
				}
			}
		}
		makeMagicBallDisappear();
		//Destroy(this);
	}

	public void makeMagicBallDisappear(){
		GetComponent<SpriteRenderer>().enabled = false;
		GetComponent<BoxCollider2D>().enabled = false;
		GetComponent<Animator>().enabled = false;
		isVisible = false;
	}

	public void recreateInFrontOfPlayer(Vector2 posInFrontOfPlayer, int direction){
		transform.position = posInFrontOfPlayer;
		this.direction = direction;
		
		GetComponent<SpriteRenderer>().enabled = true;
		GetComponent<BoxCollider2D>().enabled = true;
		countDown = 1f;
		isVisible = true;
	}
}
